package com.kr.aia.powerrp.telephone;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Random;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.SoundPool;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.MediaController;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.Toast;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.VideoView;


import com.kr.aia.powerrp.common.MainMovieClipListView;
import com.kr.aia.powerrp.common.RecController;
import com.kr.aia.powerrp.common.VideoPlayController;
import com.kr.aia.powerrp.common.VideoPlayController.onTestCompletionListener;
import com.kr.aia.powerrp.db.CustomerDBUtil;
import com.kr.aia.powerrp.db.CustomerInfoVO;
import com.kr.aia.powerrp.db.UserDBUtil;
import com.kr.aia.powerrp.db.UserInfoVO;
import com.kr.aia.powerrp.roleplay.RPDataListAdapter;
import com.kr.aia.powerrp.roleplay.RPDataVO;
import com.kr.aia.powerrp.setting.CustomerListAdapter;
import com.kr.aia.powerrp.setting.SettingMain;
import com.kr.aia.powerrp.R;

public class TAMain extends Activity implements OnClickListener{
	private static final String TAG = "TARP";
	
    private LinearLayout recorderView;
    private RecController recorderController;
    private VideoPlayController videoController;
    
    private CustomerDBUtil custDataSource;
	private UserDBUtil userDataSource;
	private ArrayList<CustomerInfoVO> custData;
	private ArrayAdapter<CustomerInfoVO> custAdapter;
	private Boolean isCustomerSelected = false;
	private UserInfoVO curUserInfo;
	private CustomerInfoVO curCustInfo;
    
    private ArrayList<Button> btArray = new ArrayList<Button>();
    
    private TextView ta_text;
    private TextView ta_cust_sel;
    private ImageButton ta_btn_record;
    private ImageButton ta_btn_stop;
    private Button ta_btn_home;
    private Button ta_btn_setting;
    private Button ta_btn_movieplay;
    private Button ta_btn_customer;
    private Button ta_btn_modify;
    private Button ta_btn_reject;
    
    private SeekBar ta_seekbar;
    private RadioGroup radioSexGroup;
    private RadioButton radioSexButton;
    
    private MediaPlayer audio_reject;
    
    private ListView taMainView;
    private ArrayList<TADataVO> taData;
    private BaseAdapter taListAdapter;
    
    
    

    private MainMovieClipListView mcv;
    
    public void setTaData(){
    	this.taData = new ArrayList<TADataVO>();
    	
    	FileInputStream fis = null;
    	BufferedReader br = null;
    	String strLine, strValue = "";
    	for(int i = 0 ; i < 15; i++){
    		try {
				fis = new FileInputStream(Environment.getExternalStorageDirectory().getPath() + "/powerRP/txt/ta/ta" + (i+1) + ".txt");
				br  = new BufferedReader(new InputStreamReader(fis));
				strValue = "";
				while( (strLine = br.readLine()) != null )
					strValue += strLine;
				
				this.taData.add(new TADataVO("title"+(i+1), strValue));
				
				//Log.e("PRP", this.taData.get(i).getContent());
			} catch (IOException e) {
				Toast toast = Toast.makeText(getApplicationContext(), "파일 저장에 실패하였습니다. 다시 시도하세요.", Toast.LENGTH_SHORT); 
				toast.show();
				finish();
			}
    	}
    }
    
    @Override
    public void onDestroy(){
    	userDataSource.close();
    	custDataSource.close();
    	Log.e(TAG, "TA DB CLOSED");
    	super.onDestroy();
    }
    
    @Override
    public void onStart(){
    	super.onStart();
    	ta_text.setText("");
    	setTaData();
    }
    
    @Override
    protected void onStop() {
        super.onStop();
        // DEALLOCATE ALL MEMORY
        if (audio_reject != null) {
            if (audio_reject.isPlaying()) {
            	audio_reject.stop();
            }
            audio_reject.release();
            audio_reject = null;
        }
    }
    
    @Override
    protected void onResume(){
    	super.onResume();
		
		curUserInfo = userDataSource.getAllData();
		custData = custDataSource.getAllData();

		/*
		custListView = (ListView) findViewById(R.id.custListView);
		custAdapter = new CustomerListAdapter(this, R.layout.setting_contact_list_row, custData);
		custAdapter.setNotifyOnChange(true);
		custListView.setAdapter(custAdapter);
		
		
		custListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            	CustomerInfoVO tmp = (CustomerInfoVO)parent.getAdapter().getItem(position);
            	((CustomerListAdapter) custAdapter).setSelectedItem(position);
            	
            	customerName.setText(tmp.getCustomerName());
        		recommender.setText(tmp.getRecommender());
        		relation.setText(tmp.getRelation());
        		customerPhoneNo.setText(tmp.getCustomerPhoneNo());

            }
        });
        */
    }
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ta_main);
        
        userDataSource = new UserDBUtil(this);
		userDataSource.open();
        
        custDataSource = new CustomerDBUtil(this);
		custDataSource.open();
        
        
        String dirName = "txt/ta";
        String dataPath = Environment.getExternalStorageDirectory().getPath() + "/powerRP/" + dirName;
        
        // 최초 실행시 폴더가 없으면 폴더 생성
        if(initDirectories(dataPath)){
        	File file;
        	FileOutputStream fos = null;
			for(int i = 0; i < 15; i++){
				file = new File(Environment.getExternalStorageDirectory().getPath() + "/powerRP/txt/ta/ta" + (i+1) + ".txt");
				// 최초 실행시 파일이 없으면 파일 생성
				if(!file.exists()) {
					try{
						fos = new FileOutputStream(file);
						fos.write((getResources().getString(R.string.ta_content_1+(i*2))).getBytes());
						fos.close();
					}catch(IOException e){
						Toast toast = Toast.makeText(getApplicationContext(), "초기화에 실패하였습니다. 다시 시도하세요.", Toast.LENGTH_SHORT); 
						toast.show();
						finish();
					}
				}
			}
        }
        
        
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        String currentDate = sdf.format(new Date());
        
        recorderView = (LinearLayout) findViewById(R.id.ta_preview);
        recorderController = new RecController(this, "ta");
        recorderView.addView(recorderController);
        
        
        
        ta_btn_home		= (Button) findViewById(R.id.ta_btn_home);
        ta_btn_reject	= (Button) findViewById(R.id.ta_btn_reject);
        ta_btn_setting	= (Button) findViewById(R.id.ta_btn_setting);
        ta_btn_movieplay= (Button) findViewById(R.id.ta_btn_movieplay);
        ta_btn_customer = (Button) findViewById(R.id.ta_btn_customer);
        ta_btn_modify	= (Button) findViewById(R.id.ta_btn_modify);
        
        ta_btn_record	= (ImageButton) findViewById(R.id.ta_btn_record);
        ta_btn_stop		= (ImageButton) findViewById(R.id.ta_btn_stop);
        
        ta_text			= (TextView) findViewById(R.id.ta_text);
        ta_cust_sel		= (TextView) findViewById(R.id.ta_customer_select_textview);
        
        ta_seekbar		= (SeekBar) findViewById(R.id.ta_seekbar);
        radioSexGroup	= (RadioGroup) findViewById(R.id.radiogroup1);
        
        ta_btn_stop.setVisibility(View.GONE);
        
        
        for(int i = 0 ; i < 15; i++){
        	int ta_id = getResources().getIdentifier("ta_list" + (i+1), "id", getPackageName());
        	btArray.add(i, (Button) findViewById(ta_id));
        }
     

        
		ta_btn_home.setOnClickListener(this);
		ta_btn_setting.setOnClickListener(this);
		ta_btn_customer.setOnClickListener(this);
		ta_btn_movieplay.setOnClickListener(this);
		ta_btn_modify.setOnClickListener(this);
		
		ta_btn_record.setOnClickListener(this);
		ta_btn_stop.setOnClickListener(this);
		ta_btn_reject.setOnClickListener(this);
		
		
		for(int i=0; i < 15; i++){
			btArray.get(i).setOnClickListener(this);
		}
		
		ta_seekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {       

		    @Override       
		    public void onStopTrackingTouch(SeekBar seekBar) {      
		        // TODO Auto-generated method stub   
		    	ta_text.setTextSize((float) (20.0 + (seekBar.getProgress() * 0.2)));
		    }       

		    @Override       
		    public void onStartTrackingTouch(SeekBar seekBar) {     
		        // TODO Auto-generated method stub      
		    }

		    @Override
		    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {     
		        // TODO Auto-generated method stub
		    }
		});
		
		ta_text.setMovementMethod(new ScrollingMovementMethod());
		
    }
    
    @Override
    public void onClick(View v){
    	
    	for(int i = 0 ; i < 15; i++){
    		
        	int ta_id = getResources().getIdentifier("ta_list" + (i+1), "id", getPackageName());
        	if(v.getId() == ta_id){
        		if(ta_cust_sel.getText().equals("")){
        			Toast toast = Toast.makeText(this, "고객을 먼저 선택하세요.", Toast.LENGTH_SHORT);
        			toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
        			toast.show();
        			break;
        		}
        		
        		String taContent = taData.get(i).getContent().replace("_고객명_", curCustInfo.getCustomerName());
        		taContent = taContent.replace("_추천인_", curCustInfo.getRecommender());
        		taContent = taContent.replace("_관계_", curCustInfo.getRelation());
        		taContent = taContent.replace("_MP명_", curUserInfo.getUserName());
        		
        		ta_text.setText(taContent);
        	}
        	//btArray.add(i, (Button) findViewById(ta_id));
        }
    	
    	switch(v.getId()){
    		case R.id.ta_btn_home:
    			finish();
    			break;
    		case R.id.ta_btn_setting:
    			Intent setting_intent = new Intent(this, SettingMain.class);
    			startActivityForResult(setting_intent, 500);
                overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);

    			break;
    		case R.id.ta_btn_customer:
    			ta_cust_sel.setText("");
            	
    			custAdapter = new CustomerListAdapter(this, R.layout.setting_contact_list_row, custData);
    			
    			ListView custList = new ListView(this);
    			custList.setAdapter(custAdapter);
    			
    			AlertDialog.Builder custBuilder = new AlertDialog.Builder(this);
    			
    			custBuilder
    			.setView(custList)	// 커스텀 뷰 지정
		   		.setPositiveButton("닫기", new DialogInterface.OnClickListener(){
		   			@Override
					public void onClick(DialogInterface dialog, int which) {
		   				dialog.dismiss();
		   				dialog.cancel();
		   			}
		   		});
    			
    			final AlertDialog custListAlertDialog = custBuilder.create();
    			custListAlertDialog.show();
    			
    			custList.setOnItemClickListener(new OnItemClickListener() {
    	            @Override
    	            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    	            	curCustInfo = (CustomerInfoVO)parent.getAdapter().getItem(position);
    	            	((CustomerListAdapter) custAdapter).setSelectedItem(position);
    	            	
    	            	ta_cust_sel.setText(curCustInfo.getCustomerName() + " " + curCustInfo.getRecommender() + " " + curCustInfo.getRelation() + " " + curCustInfo.getCustomerPhoneNo() + "    " + curUserInfo.getUserName() + " " + curUserInfo.getUserPhoneNo());
    	            	/*
    	            	if(curRPIdx == 0){
    	            		curRPTxt = "\n\n\n\n\n\n\n\n\n";
    	            		curRPIdx++;
    	            	}
    	            	curRPTxt = curRPTxt + "[" + rp.getTitle() + "]\n" +  rp.getContent() + "\n\n";
    	            	rpTextView.setText(curRPTxt);
    	            	rpDataAdapter.notifyDataSetChanged();
    	            	
    	            	//rpAlertDialog.dismiss();
    	        		*/
    	            }
    	        });
    			
    			
    			break;
    		case R.id.ta_btn_movieplay:
    			AlertDialog.Builder builder = new AlertDialog.Builder(this);
    			
    		    mcv = new MainMovieClipListView(this, "ta");
    			View mcvView = mcv.openMovieClipListView();
    			
		   		//.setIcon(R.drawable.icon_sja)		// icon 지정 후 Builder 객체 리턴
    			builder.setTitle("동영상 목록")				// title 지정
		   		//.setMessage("메시지 영역")			// 메시지 text 지정
		   		.setView(mcvView)	// 커스텀 뷰 지정
		   		// AlertDialog의 버튼 생성 & 버튼 클릭 이밴트에 대한 Listener 객체 생성/등록 
		   		.setPositiveButton("크게보기", new positiveButtonClickListener())
		   		.setNeutralButton("작게보기", new neutralButtonClickListener())
		   		.setNegativeButton("닫기", new DialogInterface.OnClickListener(){
		   			@Override
					public void onClick(DialogInterface dialog, int which) {
		   				dialog.dismiss();
		   			}
		   		});
    			builder.show(); // 지금까지 설정한 dialog를 화면에 보이고 AlertView객체를 return
    			
    			break;
    		case R.id.ta_btn_modify:
    			Intent ta_modify_intent = new Intent(this, TAModify.class);
    			//startActivity(ta_modify_intent);
    			startActivityForResult(ta_modify_intent, 500);
                overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
    			break;
    		case R.id.ta_btn_record:
    			try {
                	recorderController.startRecording();
                	ta_btn_record.setVisibility(View.GONE);
                	ta_btn_stop.setVisibility(View.VISIBLE);
                } catch (Exception e) {
                    String message = e.getMessage();
                    Log.e(TAG, "Problem Start"+message);
                    recorderController.releaseMediaRecorder();
                    ta_btn_record.setVisibility(View.VISIBLE);
                    ta_btn_stop.setVisibility(View.GONE);
                }
    			break;
    		case R.id.ta_btn_stop:
    			try{
    				recorderController.stopRecording();
    			}catch(Exception e){
    				
    			}finally{
    				ta_btn_stop.setVisibility(View.GONE);
        			ta_btn_record.setVisibility(View.VISIBLE);
    			}
    			break;
    		case R.id.ta_btn_reject:
    			
    			// get selected radio button from radioGroup
    			int selectedId = radioSexGroup.getCheckedRadioButtonId();
    			// find the radiobutton by returned id
    			radioSexButton = (RadioButton) findViewById(selectedId);
    			
    			String checkSex = "m";
    			if(radioSexButton.getText().equals("여자")){
    				checkSex = "w";
    			}
    			
    			Random rand = new Random();
    		    int mRandVal = rand.nextInt(19);
    		    int wRandVal = rand.nextInt(15);
    		    
    		    String audioFile = checkSex + mRandVal;
    		    
    		    if(checkSex.equals("w")){
    		    	audioFile = checkSex + wRandVal;
    		    }
    		    
    		    Log.e(TAG, "Random File Name : " + audioFile);
    			
    			int resID = getResources().getIdentifier(audioFile, "raw", getPackageName());
    			
    			if(audio_reject != null){
    				try {
    					if (audio_reject.isPlaying()) {
    		            	audio_reject.stop();
    		            	audio_reject.release();
    		            }
					} catch (IllegalStateException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
    			}
    			audio_reject = null;
    			audio_reject = MediaPlayer.create(this, resID);
        		audio_reject.start();
    			
    			
    			
     
    			//Toast.makeText(getApplicationContext(), resID, Toast.LENGTH_SHORT).show();
    			break;
    		/*	
    		case R.id.ta_list1:
    			ta_text.setText(taData.get(0).getContent());
    			break;
    		case R.id.ta_list2:
    			ta_text.setText(taData.get(1).getContent());
    			break;
    		case R.id.ta_list3:
    			ta_text.setText(taData.get(2).getContent());
    			break;
    		case R.id.ta_list4:
    			ta_text.setText(taData.get(3).getContent());
    			break;
    		case R.id.ta_list5:
    			ta_text.setText(taData.get(4).getContent());
    			break;
    		case R.id.ta_list6:
    			ta_text.setText(taData.get(5).getContent());
    			break;
    		case R.id.ta_list7:
    			ta_text.setText(taData.get(6).getContent());
    			break;
    		case R.id.ta_list8:
    			ta_text.setText(taData.get(7).getContent());
    			break;
    		case R.id.ta_list9:
    			ta_text.setText(taData.get(8).getContent());
    			break;
    		case R.id.ta_list10:
    			ta_text.setText(taData.get(9).getContent());
    			break;
    		case R.id.ta_list11:
    			ta_text.setText(taData.get(10).getContent());
    			break;
    		case R.id.ta_list12:
    			ta_text.setText(taData.get(11).getContent());
    			break;
    		case R.id.ta_list13:
    			ta_text.setText(taData.get(12).getContent());
    			break;
    		case R.id.ta_list14:
    			ta_text.setText(taData.get(13).getContent());
    			break;
    		case R.id.ta_list15:
    			ta_text.setText(taData.get(14).getContent());
    			break;
    		*/
    	}
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
    }

    /*
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        menu.add(0, 0, 0, "StartRecording");
        menu.add(0, 1, 0, "StopRecording");
        return super.onCreateOptionsMenu(menu);
        //return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
        case 0:
            try {
            	recorderController.startRecording();
            } catch (Exception e) {
                String message = e.getMessage();
                Log.i(null, "Problem Start"+message);
                recorderController.releaseMediaRecorder();
            }
            break;

        case 1: //GoToAllNotes
        	recorderController.stopRecording();
            break;

        default:
            break;
        }
        return super.onOptionsItemSelected(item);
    }
    */
    
    
    private String getSubstitutedContent(String orgContent){
    	String returnString = "";
    	/*
    	String custNm;
    	
    	custNm = "_고객명_";
    	orgContent.replace(custNm, "12");
	}
	break;
case R.id.ta_mod_btn_recommender:
	if(curSelectedContent == -1){
		Toast toast = Toast.makeText(getApplicationContext(), "내용을 먼저 선택하세요.", Toast.LENGTH_SHORT); 
		toast.show();
	}else{
		txt = "_추천인_";
		ta_mod_text.getText().replace(Math.min(start, end), Math.max(start, end), txt, 0, txt.length());
	}
	break;
case R.id.ta_mod_btn_relation:
	if(curSelectedContent == -1){
		Toast toast = Toast.makeText(getApplicationContext(), "내용을 먼저 선택하세요.", Toast.LENGTH_SHORT); 
		toast.show();
	}else{
		txt = "_관계_";
		ta_mod_text.getText().replace(Math.min(start, end), Math.max(start, end), txt, 0, txt.length());
	}
	break;
case R.id.ta_mod_btn_mpname:
	if(curSelectedContent == -1){
		Toast toast = Toast.makeText(getApplicationContext(), "내용을 먼저 선택하세요.", Toast.LENGTH_SHORT); 
		toast.show();
	}else{
		txt = "_MP명_";
    }
    
    */
    	return returnString;
    }
    
    public boolean initDirectories(String dataPath){
		
		if(checkSDMount()){
			File dir = new File(dataPath);
			if(!dir.exists()) {
				dir.mkdirs();
			}
		}
		return true;
		//Log.i("PRP", path);
	}
    
    public boolean checkSDMount(){
		Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);

		if(isSDPresent){
			//Toast toast = Toast.makeText(getContext(), "SD카드가 삽입 되었습니다.", Toast.LENGTH_SHORT); 
			//toast.show();
			return true;
		}else{
			Toast toast = Toast.makeText(getApplicationContext(), "SD카드가 삽입되지 않았습니다.", Toast.LENGTH_SHORT); 
			toast.show();
			return false;
		}
	}
    
    
    public class positiveButtonClickListener implements DialogInterface.OnClickListener{
    	@Override
		public void onClick(DialogInterface dialog, int which) {
			//dialog.dismiss();
			//Log.e("PRP", "----------------- " + intentUri.toString());
			if(mcv.getIntentUri() != null){
				Intent intent = new Intent();
	            intent.setAction(Intent.ACTION_VIEW);
	            intent.setDataAndType(mcv.getIntentUri(), "video/mp4");
	            startActivity(intent);
			}
		}
	};
	
	public class neutralButtonClickListener implements DialogInterface.OnClickListener{
    	@Override
		public void onClick(DialogInterface dialog, int which) {
    		videoController = new VideoPlayController(getApplicationContext(), mcv.getIntentUri().toString());
    		videoController.setOnCompletionListener(onTestClickListener);
    		
    		recorderView.removeView(recorderController);
    		recorderView.addView(videoController);
		}
	};
	
	private onTestCompletionListener onTestClickListener = new onTestCompletionListener()
    {
		@Override
		public void onCompletion(MediaPlayer arg0) {
			recorderView.removeView(videoController);
			recorderView.addView(recorderController);
		}
    };
	
	
    
}